﻿using HslCommunication.Core.Pipe;
using HslCommunication.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDevice
{
    /// <summary>
    /// Modbus RTU 串口封装
    /// </summary>
    public class SerialBase_V2 : PipeSerialPort
    {
        /// <summary>
        /// 激活HSL通信库授权
        /// </summary>
        /// <exception cref="Exception"></exception>
        public static void Activate()
        {
            // 授权示例 调用一次即可 call only once
            if (!HslCommunication.Authorization.SetAuthorizationCode("e0397905-7455-4533-8c7a-3ec89b68b2a7"))
            {
                throw new Exception("授权失败！HSL当前程序只能使用8小时！");
                //return;
            }
        }

        /// <summary>
        /// 总线锁
        /// </summary>
        public readonly object Locker = new object();

        /// <summary>
        /// 从机切换延时
        /// </summary>
        public int Delay = 10;//10ms

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="port"></param>
        /// <param name="baud"></param>
        public SerialBase_V2(string port, int baud = 38400) : base()
        {
            SerialPortInni($"{port}-{baud}-8-N-1");
            RtsEnable = false;
            DtrEnable = false;
            SleepTime = 0;
            ReceiveTimeOut = 1000;
            SleepTime = 0;
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <exception cref="Exception"></exception>
        public void OpenPort()
        {
            var openResult = OpenCommunication();
            if (!openResult.IsSuccess)
            {
                throw new Exception($"打开串口失败: {openResult.Message}");
            }
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <exception cref="Exception"></exception>
        public void ClosePort()
        {
            var closePort = CloseCommunication();
            if (!closePort.IsSuccess)
            {
                throw new Exception($"关闭串口失败: {closePort.Message}");
            }
        }
    }
}